package com.isoft.src.main.java.util;

import com.isoft.src.main.java.model.Product;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ProductFileHandler {
    private static final String PRODUCT_FILE = "C:\\Users\\yy0421\\IdeaProjects\\z.one\\项目源码\\com\\isoft\\src\\main";

    // Save products to file
    public static void saveProducts(List<Product> products) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(PRODUCT_FILE))) {
            for (Product product : products) {
                writer.write(product.getId() + "," + product.getName() + "," + product.getPrice() + "," + product.getStock());
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("Error saving products to file: " + e.getMessage());
        }
    }

    // Load products from file
    public static List<Product> loadProducts() {
        List<Product> products = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCT_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 4) {
                    String id = parts[0];
                    String name = parts[1];
                    double price = Double.parseDouble(parts[2]);
                    int stock = Integer.parseInt(parts[3]);
                    products.add(new Product(id, name, price, stock));
                }
            }
        } catch (IOException e) {
            System.err.println("Error loading products from file: " + e.getMessage());
        }
        return products;
    }
}
